package com.it.service.impl;

import com.it.common.Result;
import com.it.dao.UserMapper;
import com.it.domain.User;
import com.it.service.LoginService;
import com.it.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServImpl implements LoginService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Object login(String username, String password) {
        User user = userMapper.SelectUser(username,password);
        if(user == null){
            return null;
        }
        else{
            String token = JWTUtils.createToken(user.getId());
            Result result = Result.getinfo(token,user);
            redisTemplate.opsForValue().set("TOKEN_"+token,user,1, TimeUnit.DAYS);
            return result;
        }
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return Result.success("200","操作成功");
    }

    @Override
    public User CheckToken(String token) {
        if(token == null || token == ""){
            return null;
        }
        Map<String,Object> claims = JWTUtils.checkToken(token);

        if(claims == null){
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get("TOKEN_"+token);
        if(user == null){
            return null;
        }

        return user;
    }


}
